package com.consumer.service.impl;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.consumer.config.URLConfig;
import com.consumer.entity.*;
import com.consumer.service.DevopsDemandService;
import com.consumer.service.DevopsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class MigrationNewService {

    @Resource
    DevopsDemandService devopsDemandService;
    @Resource
    DevopsTaskService devopsTaskService;

    public void migrateDemand(String projectId) {

        //查询所有计划
        HashMap<String, Object> paramMap4 = new HashMap<>();
        String plans = HttpUtil.post(URLConfig.CONSUMER_URL + "queryAllProjectPlan", paramMap4);
        List<TPlane> planeList = JSON.parseArray(plans, TPlane.class);

        //有多个主目标的项目
        Map<String, List<TPlane>> collect = planeList.stream().collect(Collectors.groupingBy(TPlane::getSystemId));
        List<TPlane> newPlaneList = new ArrayList<>();
        Set<String> removeSet = new HashSet();
        collect.forEach((k, v) -> {
            if (v.size() == 1) {
                newPlaneList.addAll(v);
            } else {
                removeSet.add(k);
            }
        });
        if (removeSet.contains(projectId)) {
            System.out.println("项目存在多个主目标::" + projectId);
            return;
        }

        //查询所有用户
        HashMap<String, Object> paramMap6 = new HashMap<>();
        String users = HttpUtil.post(URLConfig.CONSUMER_URL + "queryAllUser", paramMap6);
        List<VUserData> userDataList = JSON.parseArray(users, VUserData.class);
        //12345 -李XX
        Map<String, String> userKV = userDataList.stream().collect(Collectors.toMap(VUserData::getAccountId, VUserData::getName));
        //12345-lixx
        Map<String, String> userKV2 = userDataList.stream().collect(Collectors.toMap(VUserData::getAccountId, VUserData::getAccountName));
        //查询出所有的 epic
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", projectId);
        String epics = HttpUtil.post(URLConfig.CONSUMER_URL + "queryEpicBySystemId", paramMap);
        List<TEpic> epicList = JSON.parseArray(epics, TEpic.class);

        buildEpic(epicList, userKV, userKV2);


        //查询出所有的 story
        HashMap<String, Object> paramMap2 = new HashMap<>();
        paramMap2.put("systemId", projectId);
        String storys = HttpUtil.post(URLConfig.CONSUMER_URL + "queryStoryBySystemId", paramMap2);
        List<TStory> storyList = JSON.parseArray(storys, TStory.class);
        //保存 story 数据
        buildStory(storyList, userKV, userKV2);


        //查询出所有的 task 任务
        HashMap<String, Object> paramMap3 = new HashMap<>();
        paramMap3.put("systemId", projectId);
        String tasks = HttpUtil.post(URLConfig.CONSUMER_URL + "queryTaskBySystemId", paramMap3);
        List<TTask> tTasks = JSON.parseArray(tasks, TTask.class);
        buildTask(tTasks, userKV, userKV2);
    }

    private void buildTask(List<TTask> taskList, Map<String, String> userKV, Map<String, String> userKV2) {
        DevopsTask devopsTask = null;
        List<DevopsTask> devopsTasks = null;
        for (TTask task : taskList) {
            devopsTask = new DevopsTask();
            devopsTask.setId(task.getTaskId());
            devopsTask.setCode("D" + System.nanoTime());
            devopsTask.setFullId(task.getEpicId() + "/" + task.getStoryId() + "/" + task.getTaskId());
            devopsTask.setIsLeaf("0");
            devopsTask.setManager(task.getMoniterUser());
            devopsTask.setManagerName(userKV.get(task.getMoniterUser()));
            devopsTask.setVersion(1L);
            devopsTask.setParentId(task.getStoryId());
            devopsTask.setTaskGroupId(task.getTaskGroupId());
            devopsTask.setPlanDetailId(task.getPlaneDetailId());
            devopsTask.setPlanId(task.getPlaneId());
            devopsTask.setProjectId(task.getSystemId());
            devopsTask.setName(task.getTitle());
            devopsTask.setSort(task.getSort());
            devopsTask.setStatus(task.getStatus());
            devopsTask.setRemark(StringUtils.isBlank(task.getRemark()) ? task.getTitle() : task.getRemark());
            devopsTask.setPredictBeginTime(task.getPredictBeginTime());
            devopsTask.setPredictEndTime(task.getPredictEndTime());
            devopsTask.setPracticalBeginTime(task.getPracticalBeginTime());
            devopsTask.setPracticalEndTime(task.getPracticalEndTime());
            devopsTask.setHoursOfWork(task.getHoursOfWork());
            devopsTask.setHoursOfWorkTruth(task.getHoursOfWorkTruth());
            devopsTask.setHoursOfWorkUnit(task.getHoursOfWorkUnit());
            devopsTask.setSource(StringUtils.isBlank(task.getSource()) ? "1" : "2");
            devopsTask.setTaskType(task.getType());
            devopsTask.setLevel(task.getLevel());
            devopsTask.setIsValid("Y");
            devopsTask.setCreateTime(task.getCreateTime());
            devopsTask.setCreateUser(task.getCreateUser());
            devopsTask.setUpdateTime(task.getUpdateTime());
            devopsTask.setUpdateUser(task.getUpdateUser());
            devopsTask.setCreateUserName(task.getCreateUser() == null ? "devops" : (userKV.get(task.getCreateUser()) == null ? "devops" : userKV.get(task.getCreateUser())));
            devopsTask.setUpdateUserName(task.getUpdateUser() == null ? "devops" : (userKV.get(task.getUpdateUser()) == null ? "devops" : userKV.get(task.getUpdateUser())));
            devopsTask.setLesseeId("devops");
            devopsTasks.add(devopsTask);
        }

        devopsTaskService.saveTaskList(devopsTasks);
    }

    private void buildStory(List<TStory> storyList, Map<String, String> userKV, Map<String, String> userKV2) {
        List<DevopsDemand> devopsDemands = new ArrayList<>();
        DevopsDemand storyDemand = null;
        for (TStory story : storyList) {
            storyDemand = new DevopsDemand();
            storyDemand.setId(story.getStoryId());
            storyDemand.setDemandSource(story.getSource() == null ? "4" : "3");
            storyDemand.setCode("D" + System.nanoTime());
            storyDemand.setDemandType(story.getType());
            storyDemand.setFullId(story.getEpicId() + "/" + story.getStoryId());
            storyDemand.setIsLeaf("1");
            storyDemand.setManager(story.getMoniterUser());
            storyDemand.setManagerAccount(userKV2.get(story.getMoniterUser()));
            storyDemand.setManagerName(userKV.get(story.getMoniterUser()));
            storyDemand.setIntroducer(story.getMoniterUser());
            storyDemand.setIntroducerAccount(userKV2.get(story.getMoniterUser()));
            storyDemand.setIntroducerName(userKV.get(story.getMoniterUser()));
            storyDemand.setParentId(story.getEpicId());
            storyDemand.setTaskGroupId(story.getTaskGroupId());
            storyDemand.setPlanDetailId(story.getPlaneDetailId());
            storyDemand.setPlanId(story.getPlaneId());
            storyDemand.setProjectId(story.getSystemId());
            storyDemand.setName(story.getTitle());
            storyDemand.setSort(story.getSort());
            storyDemand.setStatus(story.getStatus());
            storyDemand.setRemark(StringUtils.isBlank(story.getRemark()) ? story.getTitle() : story.getRemark());
            storyDemand.setCommitTime(LocalDateTime.now());
            storyDemand.setPredictBeginTime(story.getPredictBeginTime());
            storyDemand.setPredictEndTime(story.getPredictEndTime());
            storyDemand.setPracticalBeginTime(story.getPracticalBeginTime());
            storyDemand.setPracticalEndTime(story.getPracticalEndTime());
            storyDemand.setHoursOfWork(story.getHoursOfWork());
            storyDemand.setHoursOfWorkTruth(story.getHoursOfWorkTruth());
            storyDemand.setHoursOfWorkUnit(story.getHoursOfWorkUnit());
            storyDemand.setLevel(story.getLevel());
            storyDemand.setIsValid("Y");
            storyDemand.setCreateTime(story.getCreateTime());
            storyDemand.setCreateUser(story.getCreateUser());
            storyDemand.setCreateUserName(story.getCreateUser() == null ? "devops" : (userKV.get(story.getCreateUser()) == null ? "devops" : userKV.get(story.getCreateUser())));
            storyDemand.setUpdateTime(story.getUpdateTime());
            storyDemand.setUpdateUser(story.getUpdateUser());
            storyDemand.setUpdateUserName(story.getUpdateUser() == null ? "devops" : (userKV.get(story.getUpdateUser()) == null ? "devops" : userKV.get(story.getUpdateUser())));
            storyDemand.setLesseeId("devops");
            devopsDemands.add(storyDemand);
        }
        devopsDemandService.saveDemandList(devopsDemands);
    }
    private void buildEpic(List<TEpic> epicList, Map<String, String> userKV, Map<String, String> userKV2) {
        DevopsDemand epicDemand = null;
        List<DevopsDemand> devopsDemands = new ArrayList<>();
        for (TEpic epic : epicList) {
            String epicId = epic.getEpicId();
            epicDemand = new DevopsDemand();
            epicDemand.setId(epicId);
            epicDemand.setDemandSource(epic.getSource() == null ? "4" : "3");
            epicDemand.setCode("D" + System.nanoTime());
            epicDemand.setDemandType(epic.getType());
            epicDemand.setFullId(epicId);
            epicDemand.setIsLeaf("0");
            epicDemand.setManager(epic.getMoniterUser());
            epicDemand.setManagerAccount(userKV2.get(epic.getMoniterUser()));
            epicDemand.setManagerName(userKV.get(epic.getMoniterUser()));
            epicDemand.setIntroducer(epic.getMoniterUser());
            epicDemand.setIntroducerAccount(userKV2.get(epic.getMoniterUser()));
            epicDemand.setIntroducerName(userKV.get(epic.getMoniterUser()));
            epicDemand.setParentId("-1");
            epicDemand.setTaskGroupId(epic.getTaskGroupId());
            epicDemand.setPlanDetailId(epic.getPlaneDetailId());
            epicDemand.setPlanId(epic.getPlaneId());
            epicDemand.setProjectId(epic.getSystemId());
            epicDemand.setName(epic.getTitle());
            epicDemand.setSort(epic.getSort());
            epicDemand.setStatus(epic.getStatus());
            epicDemand.setRemark(StringUtils.isBlank(epic.getRemark()) ? epic.getTitle() : epic.getRemark());
            epicDemand.setCommitTime(LocalDateTime.now());
            epicDemand.setPredictBeginTime(epic.getPredictBeginTime());
            epicDemand.setPredictEndTime(epic.getPredictEndTime());
            epicDemand.setPracticalBeginTime(epic.getPracticalBeginTime());
            epicDemand.setPracticalEndTime(epic.getPracticalEndTime());
            epicDemand.setHoursOfWork(epic.getHoursOfWork());
            epicDemand.setHoursOfWorkTruth(epic.getHoursOfWorkTruth());
            epicDemand.setHoursOfWorkUnit(epic.getHoursOfWorkUnit());
            epicDemand.setLevel(epic.getLevel());
            epicDemand.setIsValid("Y");
            epicDemand.setCreateTime(epic.getCreateTime());
            epicDemand.setCreateUser(epic.getCreateUser());
            epicDemand.setCreateUserName(epic.getCreateUser() == null ? "devops" : (userKV.get(epic.getCreateUser()) == null ? "devops" : userKV.get(epic.getCreateUser())));
            epicDemand.setUpdateTime(epic.getUpdateTime());
            epicDemand.setUpdateUser(epic.getUpdateUser());
            epicDemand.setUpdateUserName(epic.getUpdateUser() == null ? "devops" : (userKV.get(epic.getUpdateUser()) == null ? "devops" : userKV.get(epic.getUpdateUser())));
            epicDemand.setLesseeId("devops");
            devopsDemands.add(epicDemand);

        }
        devopsDemandService.saveDemandList(devopsDemands);

    }

    public void migrateProductDemand(String productId) {
        HashMap<String, Object> paramMap4 = new HashMap<>();
        String plans = HttpUtil.post(URLConfig.CONSUMER_URL + "queryAllProductPlan", paramMap4);
        List<TProductPlane> planeList = JSON.parseArray(plans, TProductPlane.class);

        HashMap<String, Object> paramMap6 = new HashMap<>();
        String users = HttpUtil.post(URLConfig.CONSUMER_URL + "queryAllUser", paramMap6);
        List<VUserData> userDataList = JSON.parseArray(users, VUserData.class);

        Map<String, String> userKV = userDataList.stream().collect(Collectors.toMap(VUserData::getAccountId, VUserData::getName));
        Map<String, String> userKV2 = userDataList.stream().collect(Collectors.toMap(VUserData::getAccountId, VUserData::getAccountName));

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", productId);
        String epics = HttpUtil.post(URLConfig.CONSUMER_URL + "queryProductEpicBySystemId", paramMap);
        List<TProductEpic> epicList = JSON.parseArray(epics, TProductEpic.class);


        HashMap<String, Object> paramMap2 = new HashMap<>();
        paramMap2.put("systemId", productId);
        String storys = HttpUtil.post(URLConfig.CONSUMER_URL + "queryProductStoryBySystemId", paramMap2);
        List<TProductStory> storyList = JSON.parseArray(storys, TProductStory.class);
        Map<String, List<TProductStory>> storyListMap;
        if (Optional.ofNullable(storyList).isPresent()) {
            storyListMap = storyList.stream().collect(Collectors.groupingBy(TProductStory::getProductEpicId));
        } else {
            storyListMap = null;
        }

        HashMap<String, Object> paramMap3 = new HashMap<>();
        paramMap3.put("systemId", productId);
        String tasks = HttpUtil.post(URLConfig.CONSUMER_URL + "queryProductTaskBySystemId", paramMap3);
        List<TProductTask> tTasks = JSON.parseArray(tasks, TProductTask.class);
        Map<String, List<TProductTask>> taskListMap;
        if (Optional.ofNullable(tTasks).isPresent()) {
            taskListMap = tTasks.stream().collect(Collectors.groupingBy(TProductTask::getProductStoryId));
        } else {
            taskListMap = null;
        }

        List<DevopsDemand> devopsDemands = new ArrayList<>();
        List<DevopsTask> devopsTasks = new ArrayList<>();


        DevopsDemand epicDemand = null;
        for (TProductEpic e : epicList) {
            String epicId = e.getProductEpicId();
            epicDemand = new DevopsDemand();
            epicDemand.setId(epicId);
            if (!Optional.ofNullable(e.getSource()).isPresent() || e.getSource().equals("1") || StringUtils.isBlank(e.getSource())) {
                epicDemand.setDemandSource("4");
            }
            if (Optional.ofNullable(e.getSource()).isPresent() && e.getSource().equals("2")) {
                epicDemand.setDemandSource("3");
            }

            epicDemand.setCode("D" + System.nanoTime());
            epicDemand.setDemandType(e.getType());
            epicDemand.setFullId(epicId);
            epicDemand.setIsLeaf("0");
            epicDemand.setManager(e.getMoniterUser());
            epicDemand.setManagerAccount(userKV2.get(e.getMoniterUser()));
            epicDemand.setManagerName(userKV.get(e.getMoniterUser()));
            epicDemand.setIntroducer(e.getMoniterUser());
            epicDemand.setIntroducerAccount(userKV2.get(e.getMoniterUser()));
            epicDemand.setIntroducerName(userKV.get(e.getMoniterUser()));
            epicDemand.setParentId("-1");
            epicDemand.setTaskGroupId(e.getProductTaskGroupId());
            epicDemand.setPlanDetailId(e.getProductPlaneDetailId());
            epicDemand.setPlanId(e.getProductPlaneId());
            epicDemand.setProjectId(e.getSystemId());
            epicDemand.setName(e.getTitle());
            epicDemand.setSort(e.getSort());
            epicDemand.setStatus(e.getStatus());

            epicDemand.setRemark(StringUtils.isBlank(e.getRemark()) ? e.getTitle() : e.getRemark());

            epicDemand.setCommitTime(LocalDateTime.now());
            epicDemand.setPredictBeginTime(e.getPredictBeginTime());
            epicDemand.setPredictEndTime(e.getPredictEndTime());
            epicDemand.setPracticalBeginTime(e.getPracticalBeginTime());
            epicDemand.setPracticalEndTime(e.getPracticalEndTime());
            epicDemand.setHoursOfWork(e.getHoursOfWork());
            epicDemand.setHoursOfWorkTruth(e.getHoursOfWorkTruth());
            epicDemand.setHoursOfWorkUnit(e.getHoursOfWorkUnit());
            epicDemand.setLevel(e.getLevel());
            epicDemand.setIsValid("Y");
            epicDemand.setCreateTime(e.getCreateTime());
            epicDemand.setCreateUser(e.getCreateUser());
            epicDemand.setCreateUserName(e.getCreateUser() == null ? "devops" : (userKV.get(e.getCreateUser()) == null ? "devops" : userKV.get(e.getCreateUser())));
            epicDemand.setUpdateTime(e.getUpdateTime());
            epicDemand.setUpdateUser(e.getUpdateUser());
            epicDemand.setUpdateUserName(e.getUpdateUser() == null ? "devops" : (userKV.get(e.getUpdateUser()) == null ? "devops" : userKV.get(e.getUpdateUser())));
            epicDemand.setLesseeId("devops");
            devopsDemands.add(epicDemand);
            //处理 story
            if (Optional.ofNullable(storyListMap).isPresent() && storyListMap.get(e.getProductEpicId()) != null) {
                DevopsDemand storyDemand = null;
                List<TProductStory> tStories = storyListMap.get(epicId);
                for (TProductStory story : tStories) {
                    String storyId = story.getProductStoryId();
                    storyDemand = new DevopsDemand();
                    storyDemand.setId(storyId);
                    if (!Optional.ofNullable(e.getSource()).isPresent() || e.getSource().equals("1") || StringUtils.isBlank(e.getSource())) {
                        storyDemand.setDemandSource("4");
                    }
                    if (Optional.ofNullable(e.getSource()).isPresent() && e.getSource().equals("2")) {
                        storyDemand.setDemandSource("3");
                    }
                    storyDemand.setCode("D" + System.nanoTime());
                    storyDemand.setDemandType(story.getType());
                    storyDemand.setFullId(epicId + "/" + storyId);
                    storyDemand.setIsLeaf("1");
                    storyDemand.setManager(story.getMoniterUser());
                    storyDemand.setManagerAccount(userKV2.get(story.getMoniterUser()));
                    storyDemand.setManagerName(userKV.get(story.getMoniterUser()));
                    storyDemand.setIntroducer(story.getMoniterUser());
                    storyDemand.setIntroducerAccount(userKV2.get(story.getMoniterUser()));
                    storyDemand.setIntroducerName(userKV.get(story.getMoniterUser()));
                    storyDemand.setParentId(story.getProductEpicId());
                    storyDemand.setTaskGroupId(story.getProductTaskGroupId());
                    storyDemand.setPlanDetailId(story.getProductPlaneDetailId());
                    storyDemand.setPlanId(story.getProductPlaneId());
                    storyDemand.setProjectId(story.getSystemId());
                    storyDemand.setName(story.getTitle());
                    storyDemand.setSort(story.getSort());
                    storyDemand.setStatus(story.getStatus());
                    storyDemand.setRemark(StringUtils.isBlank(story.getRemark()) ? story.getTitle() : story.getRemark());
                    storyDemand.setCommitTime(LocalDateTime.now());
                    storyDemand.setPredictBeginTime(story.getPredictBeginTime());
                    storyDemand.setPredictEndTime(story.getPredictEndTime());
                    storyDemand.setPracticalBeginTime(story.getPracticalBeginTime());
                    storyDemand.setPracticalEndTime(story.getPracticalEndTime());
                    storyDemand.setHoursOfWork(story.getHoursOfWork());
                    storyDemand.setHoursOfWorkTruth(story.getHoursOfWorkTruth());
                    storyDemand.setHoursOfWorkUnit(story.getHoursOfWorkUnit());
                    storyDemand.setLevel(story.getLevel());
                    storyDemand.setIsValid("Y");
                    storyDemand.setCreateTime(story.getCreateTime());
                    storyDemand.setCreateUser(story.getCreateUser());
                    storyDemand.setCreateUserName(story.getCreateUser() == null ? "devops" : (userKV.get(story.getCreateUser()) == null ? "devops" : userKV.get(story.getCreateUser())));
                    storyDemand.setUpdateTime(story.getUpdateTime());
                    storyDemand.setUpdateUser(story.getUpdateUser());
                    storyDemand.setUpdateUserName(story.getUpdateUser() == null ? "devops" : (userKV.get(story.getUpdateUser()) == null ? "devops" : userKV.get(story.getUpdateUser())));
                    storyDemand.setLesseeId("devops");
                    devopsDemands.add(storyDemand);
                    if (Optional.ofNullable(taskListMap).isPresent() && taskListMap.get(storyId) != null) {
                        List<TProductTask> tTasks1 = taskListMap.get(storyId);
                        DevopsTask devopsTask = null;
                        for (TProductTask t : tTasks1) {
                            devopsTask = new DevopsTask();
                            String taskId = t.getProductTaskId();
                            devopsTask.setId(taskId);
                            devopsTask.setCode("D" + System.nanoTime());
                            devopsTask.setFullId(epicId + "/" + storyId + "/" + taskId);
                            devopsTask.setIsLeaf("0");
                            devopsTask.setParentId(storyId);
                            devopsTask.setManager(t.getMoniterUser());
                            devopsTask.setManagerName(userKV.get(t.getMoniterUser()));
                            devopsTask.setVersion(1L);
                            devopsTask.setSource(StringUtils.isBlank(t.getSource()) ? "1" : "2");
                            devopsTask.setTaskType(t.getType());
                            devopsTask.setParentId(storyId);
                            devopsTask.setTaskGroupId(t.getProductTaskGroupId());
                            devopsTask.setPlanDetailId(t.getProductPlaneDetailId());
                            devopsTask.setPlanId(t.getProductPlaneId());
                            devopsTask.setProjectId(t.getSystemId());
                            devopsTask.setName(t.getTitle());
                            devopsTask.setSort(t.getSort());
                            devopsTask.setStatus(t.getStatus());
                            devopsTask.setPredictBeginTime(t.getPredictBeginTime());
                            devopsTask.setPredictEndTime(t.getPredictEndTime());
                            devopsTask.setPracticalBeginTime(t.getPracticalBeginTime());
                            devopsTask.setPracticalEndTime(t.getPracticalEndTime());
                            devopsTask.setHoursOfWork(t.getHoursOfWork());
                            devopsTask.setHoursOfWorkTruth(t.getHoursOfWorkTruth());
                            devopsTask.setHoursOfWorkUnit(t.getHoursOfWorkUnit());
                            devopsTask.setLevel(t.getLevel());
                            devopsTask.setIsValid("Y");
                            devopsTask.setCreateTime(t.getCreateTime());
                            devopsTask.setCreateUser(t.getCreateUser());
                            devopsTask.setUpdateTime(t.getUpdateTime());
                            devopsTask.setUpdateUser(t.getUpdateUser());
                            devopsTask.setCreateUserName(t.getCreateUser() == null ? "devops" : (userKV.get(t.getCreateUser()) == null ? "devops" : userKV.get(t.getCreateUser())));
                            devopsTask.setUpdateUserName(t.getUpdateUser() == null ? "devops" : (userKV.get(t.getUpdateUser()) == null ? "devops" : userKV.get(t.getUpdateUser())));
                            devopsTask.setLesseeId("devops");
                            devopsTasks.add(devopsTask);
                        }
                    }
                }
            }
        }
        if (Optional.ofNullable(devopsTasks).isPresent()) {
            devopsTaskService.saveTaskList(devopsTasks);
        }
        if (Optional.ofNullable(devopsDemands).isPresent()) {
            devopsDemandService.saveDemandList(devopsDemands);
        }
    }

}
